package com.lxx.wiki.service;


import com.lxx.wiki.domain.entity.LoginUser;
import com.lxx.wiki.domain.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询对于用户名的user
        User user = userService.selectByLoginName(username);

        // 如果查找不到，抛出异常
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        // 模拟数据库查询该用户权限
        List<String> permissions = List.of("list");

        // 构造UserDetails返回
        LoginUser loginUser = LoginUser.builder()
                .user(user)
                .permissions(permissions)
                .build();

        return loginUser;
    }
}
